package com.ad.pet.wxapi;


import android.content.Context;
import android.widget.Toast;

import com.ad.pet.R;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.constant.Constant;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;

/**
 * Created by SEELE on 2018/4/8.
 */

public class WXPayUtils {
    private IWXAPI msgApi;
    private Context mContext;

    public WXPayUtils(Context context) {
        msgApi = WXAPIFactory.createWXAPI(context, Constant.APP_ID);
        mContext = context;
    }

    /**
     * 判断是否支持微信
     * @return
     */
    public boolean isWxAppInstalledAndSupported() {


        boolean bIsWXAppInstalledAndSupported = msgApi .isWXAppInstalled() && msgApi.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;

        return bIsWXAppInstalledAndSupported;
    }
    public void doPay(String jsonString) {
        try{

            JSONObject json = new JSONObject(jsonString);
            if(null != json && !json.has("retcode") ){
                PayReq req = new PayReq();
                //req.appId = "wxf8b4f85f3a794e77";
                // 测试用appId
                //订单参数
                req.appId           = json.getString("appid");
                req.partnerId       = json.getString("partnerid");
                req.prepayId        = json.getString("prepayid");
                req.nonceStr        = json.getString("noncestr");
                req.timeStamp       = json.getString("timestamp");
                req.packageValue    = json.getString("packageValue");
                req.sign            = json.getString("sign");
                req.extData         = json.getString("extra"); // optional
                // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                ToastUtil.getToastUtil().showShort(mContext.getString(R.string.nofiing_wxpay));
                msgApi.sendReq(req);

            }else{
                Toast.makeText(mContext, mContext.getString(R.string.http_error500_msg), Toast.LENGTH_SHORT).show();
            }
        }catch(Exception e){
            Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }



}